package com.ssy.lingxi.pay.utils;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @Author xiaomai
 * @Description RestTemplate工具类
 * @Date 2022/3/14 11:15
 **/
@Configuration
@Component
public class RestTemplateUtil {

    @Resource
    private RestTemplateBuilder builder;

    private RestTemplate restTemplate;

    @Bean
    public RestTemplate restTemplate() {
        restTemplate = builder.build();
        return restTemplate;
    }

    private final Logger log = LoggerFactory.getLogger(RestTemplateUtil.class);

    /**
     * 发送post请求并返回json数据
     *
     * @param url
     * @param paramMap
     * @param description
     * @return
     */
    public String doPost(String url, Object paramMap, String description) {
        log.info("{} 请求参数： {}", description, paramMap.toString());
        log.info("{} 请求url： {}", description, url);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity httpEntity = new HttpEntity<>(paramMap , headers);
        ResponseEntity<String> response = restTemplate.postForEntity(url, httpEntity, String.class);
        log.info("{} 返回信息： {}", description, response);
        return response.getBody();
    }

    /**
     * 发送get请求并返回json数据
     *
     * @param url
     * @return
     */
    public String doGet(String url) {
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        return response.getBody();
    }

    public String doPost(String url, String paramMap) {
        ResponseEntity<String> response = restTemplate.postForEntity(url, paramMap, String.class);
        return response.getBody();
    }

}
